﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ivy.UserRegistration.Entity;
using Ivy.UserRegistration.BusinessLogic;
using Hsmp.SocietyAdmin.Entity;
using Hsmp.SocietyAdmin.BusinessLogic;
using HSMPWeb.ViewEntity;

namespace HSMPWeb.UserControls
{
    public partial class HsmpLoginControl : System.Web.UI.UserControl
    {
        

        #region Constructor & Destructor
        #endregion Constructor & Destructor

        #region Properties
        #endregion Properties

        #region Public Methods
        #endregion Public Methods

        #region Events
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitializeScreen();
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            UserRegistrationBus lUserRegistrationBus = new UserRegistrationBus();
            if (lUserRegistrationBus.Login(this.txtUserID.Text, this.txtPassword.Text))
            {
                User lUser = lUserRegistrationBus.GetUserByLoginID(this.txtUserID.Text);
                InitializeAuthenticatedUserSection(lUser);
            }
            else
            {
                this.lblLoginFailure.Text = "Login Failure - Usename and password are not matching";
            }
         }

        protected void dlsSociety_SelectedIndexChanged(object sender, EventArgs e)
        {
            SocietyRegistrationBus lSocietyRegistrationBus = new SocietyRegistrationBus();
            UserContext UserSession = (UserContext)Session["UserContext"];
            UserSession.CurrentSociety = lSocietyRegistrationBus.GetSelectedScoietyByID(this.dlsSociety.SelectedValue);
            Session["UserContext"] = UserSession;
            FillLookUpDataForRoles(UserSession.CurrentSociety.SocietyKey);
        }

        protected void dlsRole_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void btnSocityRoleSelection_Click(object sender, EventArgs e)
        {
           
            if (this.dlsSociety.SelectedIndex == -1)
            {
                this.lblInvalidSelection.Text = "Please select a society";
            }
            else
            {
                if (this.dlsRole.SelectedIndex == -1)
                {
                    this.lblInvalidSelection.Text = "Please select a Role";
                }
                else
                {
                    UserRegistrationBus lUserRegistrationBus = new UserRegistrationBus();
                    SocietyRegistrationBus lSocietyRegistrationBus = new SocietyRegistrationBus();
                    this.lblInvalidSelection.Text = string.Empty;

                    UserContext UserSession = (UserContext)Session["UserContext"];
                    UserSession.CurrentSociety = lSocietyRegistrationBus.GetSelectedScoietyByID(this.dlsSociety.SelectedValue);
                    UserSession.CurrentRole = lUserRegistrationBus.GetSelectedSys_RoleMasterByID(Convert.ToInt32(this.dlsRole.SelectedValue));
                    Session["UserContext"] = UserSession;

                    this.lblCurrentSelectedSociety.Text = "You are currently signed in as member of [" + UserSession.CurrentSociety.SocietyName + "]";
                    this.lblCurrentSelectedRole.Text = "You current role is [" + UserSession.CurrentRole.RoleName + "]";
                    this.DivSocietyAndRoleSelection.Visible = false;
                    this.DivSocietyRoleConfirmation.Visible = true;
                }
            }
            



        }

        protected void btnLogout_Click(object sender, EventArgs e)
        {
            Session.Clear();
            Session.Abandon();
            Response.Redirect(Request.Url.AbsolutePath);
        }

        protected void btnConfirm_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/HsmpHomePage1.aspx");
        }
        #endregion Events

        #region Private Methods

        private void ClearScreen()
        {
            this.txtUserID.Text = string.Empty;
            this.txtPassword.Text = string.Empty;
            this.lblLoginFailure.Text = string.Empty;

            this.dlsSociety.Items.Clear();
            this.dlsRole.Items.Clear();
            this.lblInvalidSelection.Text = string.Empty;

            this.lblCurrentSelectedSociety.Text = string.Empty;
            this.lblCurrentSelectedRole.Text = string.Empty;

        }

        private void InitializeScreen()
        {
            ClearScreen();

            this.DivLoginSection.Visible = true;
            this.DivSuccessfullSection.Visible = false;
            this.DivSocietyAndRoleSelection.Visible = false;
            this.DivSocietyRoleConfirmation.Visible = false;

        }

        private void InitializeAuthenticatedUserSection(User pUser)
        {
            this.lblLoginSuccessful.Text = "Welcome " + pUser.UserFirstName + " " + pUser.UserLastName;
            
            UserRegistrationBus lUserRegistrationBus = new UserRegistrationBus();
            User lUser = new User();
            lUser = lUserRegistrationBus.GetUserByLoginID(txtUserID.Text.Trim());
            
            UserContext UserSession = new UserContext();
            UserSession.UserIPAddress = GetUserIPAddress();
            UserSession.UserBrowser = HttpContext.Current.Request.Browser.Browser;
            UserSession.CurrentUser = pUser;
            
            UserSession.UserRoles = lUserRegistrationBus.GetAllRolesForSelectedUser(pUser.UserKey);
            Session["UserContext"] = UserSession;
            if (!lUser.UserIsVerified)
            {
                Response.Redirect("~/Pages/UserVerification.aspx");
            }
            else
            {
                InitializeRoleSectionForAuthenticatedUser();
            }
        }

        private void InitializeRoleSectionForAuthenticatedUser()
        {
            this.DivLoginSection.Visible = false;
            this.DivSuccessfullSection.Visible = true;
            this.dlsSociety.Items.Clear();
            this.dlsRole.Items.Clear();
            
            UserRegistrationBus lUserRegistrationBus = new UserRegistrationBus();
            SocietyRegistrationBus lSocietyRegistrationBus = new SocietyRegistrationBus();

            UserContext tempUserSession = (UserContext)Session["UserContext"];
            if (tempUserSession.UserRoles.Count > 0)
            {
                if (tempUserSession.UserRoles.Count > 1)
                {
                    //This is applicable when there are multiple records for the logged in user in the UserRole table.
                    FillLookUpDataForSocietyList();
                    this.DivSocietyAndRoleSelection.Visible = true;
                }
                else
                {
                    //This is applicable when there is only one record for the logged in user in the UserRole table. (that means one societykey with one rolekey)

                    this.DivSocietyAndRoleSelection.Visible = false;
                    UserContext UserSession = (UserContext)Session["UserContext"];
                    UserSession.CurrentSociety = lSocietyRegistrationBus.GetSelectedScoietyByID(tempUserSession.UserRoles[0].UserSocietyKey.ToString());
                    UserSession.CurrentRole = lUserRegistrationBus.GetSelectedSys_RoleMasterByID(tempUserSession.UserRoles[0].UserRoleKey);
                    Session["UserContext"] = UserSession;
                    this.lblCurrentSelectedSociety.Text = "You are currently signed in as member of [" + UserSession.CurrentSociety.SocietyName + "]";
                    this.lblCurrentSelectedRole.Text = "You current role is [" + UserSession.CurrentRole.RoleName + "]";
                    this.DivSocietyRoleConfirmation.Visible = true;
                }
            }
            else
            {
                //This is applicable when there is no record in UserRole table for the logged in user
                this.DivSocietyAndRoleSelection.Visible = false;
                this.lblCurrentSelectedSociety.Text = "You are currently not signed in as member of any society";
                this.lblCurrentSelectedRole.Text = "You singed as a guest user";
                this.DivSocietyRoleConfirmation.Visible = true;
            }
        }

        private void FillLoadLookUpData()
        {
        }
        private void FillLookUpDataForSocietyList()
        {
            this.dlsSociety.Items.Clear();
            this.dlsRole.Items.Clear();
            this.lblInvalidSelection.Text = string.Empty;

            SocietyRegistrationBus lSocietyRegistrationBus = new SocietyRegistrationBus();

            UserContext tempUserSession = (UserContext)Session["UserContext"];

            foreach (UserRole TempUserRole in tempUserSession.UserRoles)
            {
                Society lSociety = lSocietyRegistrationBus.GetSelectedScoietyByID(TempUserRole.UserSocietyKey.ToString());
                if (this.dlsSociety.Items.FindByValue(lSociety.SocietyKey.ToString()) == null)
                {
                    this.dlsSociety.Items.Add(new ListItem(lSociety.SocietyName, lSociety.SocietyKey.ToString()));
                }
            }
            if (this.dlsSociety.Items.Count == 1) 
            {
                //This is applicable when for the logged in user there are multiple records in UserRole table but with same society key and different role keys
                //this.dlsSociety.SelectedIndex = 0;
                //this.dlsSociety.Enabled = false;

                UserContext UserSession = (UserContext)Session["UserContext"];
                UserSession.CurrentSociety = lSocietyRegistrationBus.GetSelectedScoietyByID(this.dlsSociety.SelectedValue);
                Session["UserContext"] = UserSession;
                FillLookUpDataForRoles(UserSession.CurrentSociety.SocietyKey);
            }
            else
            {
                //This is applicable then for the logged in user there are multiple records in UserRole table with multiple society key
                //Filling up of dlsRole list will be triggered once a society is selected by the user. [For details see dlsSociety_SelectedIndexChanged() event]
                //this.dlsSociety.SelectedIndex = -1;
                //this.dlsSociety.Enabled = true;
                if (this.dlsSociety.SelectedItem.Text != string.Empty)
                {
                    FillLookUpDataForRoles(Convert.ToInt32(this.dlsSociety.SelectedValue));
                }
            }
            
        }

        private void FillLookUpDataForRoles(int pSocietyKey)
        {
            this.dlsRole.Items.Clear();
            this.lblInvalidSelection.Text = string.Empty;

            UserRegistrationBus lUserRegistrationBus = new UserRegistrationBus();

            UserContext tempUserSession = (UserContext)Session["UserContext"];
            foreach (UserRole TempUserRole in tempUserSession.UserRoles)
            {
                if (TempUserRole.UserSocietyKey == pSocietyKey)
                {
                    Sys_RoleMaster lRole = lUserRegistrationBus.GetSelectedSys_RoleMasterByID(TempUserRole.UserRoleKey);
                    if (this.dlsRole.Items.FindByValue(lRole.RoleKey.ToString()) == null)
                    {
                        this.dlsRole.Items.Add(new ListItem(lRole.RoleName, lRole.RoleKey.ToString()));
                    }
                }
            }
            if (this.dlsRole.Items.Count == 1)
            {
                //This is applicable when for the logged in user and the selected society there is only one role available in the UserRole table
                //this.dlsRole.SelectedIndex = 0;
                //this.dlsRole.Enabled = false;
                UserContext UserSession = (UserContext)Session["UserContext"];
                UserSession.CurrentRole = lUserRegistrationBus.GetSelectedSys_RoleMasterByID(Convert.ToInt32(this.dlsRole.SelectedValue));
                Session["UserContext"] = UserSession;

            }
            
        }

        private string GetUserIPAddress()
        {
            //The X-Forwarded-For (XFF) HTTP header field is a de facto standard for identifying the originating IP address of a 
            //client connecting to a web server through an HTTP proxy or load balancer
            string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(ip))
            {
                ip = HttpContext.Current.Request.UserHostAddress;
                if (string.IsNullOrEmpty(ip))
                {
                    ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
            }
            return ip;
        }
        #endregion Private Methods

    }
}